import {
  USER_SPECICAL_INFO,
  THIRD_SESSION_KEY,
  USER_INFO
} from "../utils/constant";
import { wxJsCode2Sessionbak } from "../api/api";
import {store} from '@/store/index'

let env = store.state.systemInfo.environment;

function checkSession(parm) {
    wxCheckSession(parm);
}
/**
 * 普通微信checkSession
 * @param {*} {success: 成功后执行}
 * @returns 
 */
async function wxCheckSession(parm) {
  return new Promise(async (success, fail) => {
    let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO);
    try {
      let [error, sessionRes] = await uni.checkSession({});
      console.log(sessionRes);
      if (sessionRes.errMsg == 'checkSession:ok' && !parm.force) {
        if (!userSpecialInfo || !userSpecialInfo[THIRD_SESSION_KEY] || !userSpecialInfo["unionid"] || userSpecialInfo["expires_in"] < Date.now()) {
          // session过期或不存在
          console.log('session time out');
          // 重新登录
          await wxminaLogin(parm);
        } else {
          loginSuccess(userSpecialInfo);
          if ((typeof parm.success) == 'function') {
            // 调用外部传入的参数
            parm.success();
          }
          success();
          // session有效
          console.log('login success~');
        }
      } else {
        // fail({ errMsg: '微信api checkSession调用失败'});
        console.error('checkSession unknown error..');
        await wxminaLogin(parm);
      }
    } catch (err) {
      console.log('home => onShow >> checkSession >> 👇');
      console.log(err);
      await wxminaLogin(parm);
    }
  });
}

/**
 * 普通微信login
 * 如果登录过期，则发起登录流程，更新登录状态
 * @param {*} {success: 成功后执行}
 * @returns
 */
async function wxminaLogin(parm) {
  return new Promise(async (success, fail) => {
    console.log('登录中..');
    uni.showLoading({
      mask: true, //显示透明蒙层，防止触摸穿透,
    });
    try {
      // 发起用户登录流程，获取JsCode先
      let [error, loginres] = await uni.login();
      console.log('wx.login >>>' + JSON.stringify(loginres));
      if (loginres.code) {
        // 访问服务器，更新session_key
        let c2sres = await wxJsCode2Sessionbak({
          query: {
            code: loginres.code,
            fxInviterMinimemberId: parm.fxInviterMinimemberId || ''
            //DEV 如果是第三方平台 需取消注释
            // component_appid: COMPONENT_APPID
          }
        });
        uni.hideLoading();
        // 登录正常
        console.log('wxJsCode2Session >>>');
        console.log(c2sres);
        if (c2sres.data && c2sres.data.data && c2sres.data.data.unionid) {
          let rlt = c2sres.data.data;
          loginSuccess(rlt);
          console.log('setStorageSync userSpecialInfo >> ' + JSON.stringify(rlt));
          // 登录成功
          if ((typeof parm.success) == 'function') {
            // 调用外部传入的参数
            parm.success();
          }
          success();
          return;
        } else {
          console.log('wxJsCode2Session获取session_key失败..');
          loginFail(parm);
        }
      } else {
        loginFail(parm);
      }
    } catch (error) {
      console.log(error);
      loginFail(parm);
    }
  });
}

function loginSuccess(parm) {
  // 存储全局userInfo
  store.commit('setUserInfo', parm);
  uni.setStorageSync(USER_SPECICAL_INFO, parm);
}
function loginFail(parm) {
  uni.hideLoading();
  uni.showModal({
    title: '登录失败', //提示的标题,
    content: '系统自动登录失败, 请点击重新登录', //提示的内容,
    showCancel: false, //是否显示取消按钮,
    confirmText: '重新登录', //确定按钮的文字，默认为取消，最多 4 个字符,
    confirmColor: '#3CC51F', //确定按钮的文字颜色,
    success: async res => {
      if (res.confirm) {
        await wxminaLogin(parm);
      }
    }
  });
}

module.exports = {
  checkSession: checkSession,
}
